import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import {
	User,
	Config,
	GuestLogin
} from '@/common/api.js'
import {
	getUser,
	getToken
} from '@/common/common.js'
import {
	getClientId
} from '@/common/getClientId.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	getters,
	state: {
		systemInfo: null,
		appHide: false,
		userinfo: getUser(),
		path: '/pages/home/home',
		pusherMode: 0,
		config: {
			base_ad_url: ''
		},
		video_list: [],
		nav_index: 0,
		token: getToken()
	},
	mutations: {
		SET_NAV_INDEX(state, index) {
			state.nav_index = index
		},
		setSystemInfo(state, data) {
			state.systemInfo = data
		},
		setAppHide(state, data) {
			state.appHide = data
		},
		setUserinfo(state, data) {
			state.userinfo = data
			uni.setStorage({
				key: 'userinfo',
				data,
				success: () => {}
			})
		},
		setPath(state, path) {
			state.path = path
		},
		setPusherMode(state, data) {
			state.pusherMode = data
		},
		setConfig(state, data) {
			state.config = data
		},
		setVideoList(state, data) {
			state.video_list = data
		}
	},
	actions: {
		async updateUserinfo({
			commit
		}) {
			let did = await getClientId();
			GuestLogin({
				device_id: did
			}).then(({
				code,
				data
			}) => {
				uni.setStorageSync('TOKEN', data)
				User().then(({
					code,
					data
				}) => {
					if (code === 200) {
						commit('setUserinfo', data)
						uni.setStorageSync('userinfo', data)
					}
				})
			})
		},
		getConfig({
			commit
		}, key = 'base') {
			Config({
				key
			}).then(({
				code,
				data
			}) => {
				if (code === 200) {
					commit('setConfig', data)
				}
			})
		}
	}
})

export default store